//
//  HomeViewModle.m
//  Exchange
//
//  Created by 张庆勇 on 2019/1/9.
//  Copyright © 2019年 张庆勇. All rights reserved.
//

#import "HomeViewModel.h"
#import "SymbolClass.h"
#import "AssetsModle.h"
@implementation HomeViewModel
#pragma mark - 通用的接口
+ (void)getUserWithDic:(NSDictionary *)dic url:(NSString *)url callBack:(void(^)(BOOL isSuccess,id callBack))callback;
{
    [self GETWithHost:@"" path:url param:dic cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if ([responseObject[@"code"] integerValue]==0)//成功
        {
            [EXUserManager savepersonalData:[Userinfo mj_objectWithKeyValues:responseObject[@"result"]]];
            [EXUserManager saveRealName:responseObject[@"result"][@"identity_status"]];
            [EXUserManager saveauthenticated:responseObject[@"result"][@"identity_authenticated"]];
            callback(YES,responseObject);
       
        }else
        {
            callback(NO,responseObject);
        }
        
    } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
/* 通用API*/
+ (void)httpHostWithHost:(NSString *)host Dic:(NSDictionary *)dic url:(NSString *)url callBack:(void(^)(BOOL isSuccess,id callBack))callback;
{
    if ([host isEqualToString:HOSTGET])
    {
        [self GETWithHost:@"" path:url param:dic cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"code"] integerValue]==0)//成功
            {
                callback(YES,responseObject);
                
            }else
            {
                callback(NO,responseObject);
                NSLog(@"-================================>%@",url);
             
                
            }
        } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
//             [EXUnit showMessage:Localized(@"httpsHost_message")];
        }];
    }else
    {
        [self POSTWithHost:@"" path:url param:dic cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            if ([responseObject[@"code"] integerValue]==0)
            {
                
                callback(YES,responseObject);
            }else
            {
                callback(NO,responseObject);
               
                
            }
        } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
//          [EXUnit showMessage:Localized(@"httpsHost_message")];
            
        }];
    }
    
}
#pragma mark - 首页
/*获取汇率*/
+ (void)getCurrencyWithDic:(NSDictionary *)dic url:(NSString *)url callBack:(void(^)(BOOL isSuccess,id callBack))callback;
{
    [self GETWithHost:@"" path:url param:dic cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"code"] integerValue]==0)//成功
        {
             [EXUserManager saveCurrencyData:[Currency mj_objectWithKeyValues:responseObject[@"result"]]];
            
             callback(YES,nil);
        }else
        {
            callback(NO,nil);
        }
        
    } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        callback(NO,nil);
    }];
}
/*配置size*/
+ (void)getSiteWithDic:(NSMutableDictionary *)dic url:(NSString *)url callBack :(void(^)(BOOL isSuccess,id callBack)) callback;
{
    [self GETWithHost:@"" path:url param:dic cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"code"] integerValue]==0)//成功
        {
            NSString * email = responseObject[@"result"][@"service_email"];
            [AppDelegate shareAppdelegate].emailSite = [NSString stringWithFormat:@"%@ %@",Localized(@"Google_verification_message"),email];
            [AppDelegate shareAppdelegate].sizeId = responseObject[@"result"][@"id"];
            [AppDelegate shareAppdelegate].recommend_code_force = responseObject[@"result"][@"recommend_code_force"];
            [AppDelegate shareAppdelegate].default_register_method = responseObject[@"result"][@"default_register_method"];
            [AppDelegate shareAppdelegate].is_preaudit =  responseObject[@"result"][@"is_preaudit"];
            [AppDelegate shareAppdelegate].privilages = responseObject[@"result"][@"privilages"];
            [AppDelegate shareAppdelegate].name = responseObject[@"result"][@"name"];
            [AppDelegate shareAppdelegate].otc_asset = responseObject[@"result"][@"otc_asset"];
            [AppDelegate shareAppdelegate].otc_currency = responseObject[@"result"][@"otc_currency"];
           
            callback(YES,nil);
            
        }else
        {
            callback(NO,responseObject);
            NSLog(@"-================================>%@",url);
            
            
        }
    } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         callback(NO,error);
        
    }];

}

/*获取bannerList*/
+ (void)getbannerListWithDic:(NSDictionary *)dic url:(NSString *)url callBack :(void(^)(BOOL isSuccess,id callBack)) callback;
{
    [self httpHostWithHost:HOSTGET Dic:dic url:url callBack:^(BOOL isSuccess, id callBack) {
        if (isSuccess) {
            NSArray *list = callBack[@"result"];
            callback(YES,list);
        }else
        {
            [EXUnit showMessage:callBack[@"message"]];
            callback(NO,callBack[@"message"]);
        }
    }];
}
/*获取公告*/
+ (void)getArticleListWithDic:(NSDictionary *)dic url:(NSString *)url callBack :(void(^)(BOOL isSuccess,id callBack)) callback;
{

    
    [self GETWithHost:@"" path:url param:dic cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"code"] integerValue]==0)//成功
        {
            NSArray *list = responseObject[@"result"][@"records"];
            callback(YES,[NewsModle mj_objectArrayWithKeyValuesArray:list]);
            
        }
    } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        callback(NO,error);
        
    }];
    
}
/*获取最新交易对*/
+ (void)getSymbolDataListWithDic:(NSDictionary *)dic url:(NSString *)url callBack :(void(^)(BOOL isSuccess,id callBack)) callback;
{
  
    [self httpHostWithHost:HOSTGET Dic:dic url:url callBack:^(BOOL isSuccess, id callBack) {
        if (isSuccess) {
            NSArray *list = callBack[@"result"];
            callback(YES,[SymbolModle mj_objectArrayWithKeyValuesArray:list]);
        }else
        {
              [EXUnit showMessage:callBack[@"message"]];
            callback(NO,callBack[@"message"]);
        }
    }];
}

/*获取最新k交易对并切排序返回新的数组*/
+ (void)getFirestSymbolWithArticlelArray:(NSMutableArray *)articlelArray
                             ataWithDeal:(NSString *)deal
                                  volume:(NSString *)volume
                                    high:(NSString *)high
                                    open:(NSString *)open
                                    last:(NSString *)last
                                     low:(NSString *)low
                                    name:(NSString *)name
                               dataArray:(NSMutableArray *)dataArray
                          recommendArray:(NSMutableArray *)recommendArray
                                  DICKEY:(NSString *)DICKEY
                              mutableDic:(NSMutableDictionary *)mutableDic
                                callBack:(void(^)(NSMutableArray * dataArray,NSMutableArray * recommendArray,NSMutableDictionary * mutableDic))callback;
{
    
   
    SymbolModle * sModle;
    for (int i =0 ; i<articlelArray.count; i++)
    {
        SymbolModle * Symbomodle = articlelArray[i];
        
        if ([name isEqualToString:Symbomodle.symbol]) {
            
            sModle = articlelArray[i];
        }
    }
    HomeModle * modle = [[HomeModle alloc] init];
    modle.quote_asset = sModle.quote_asset;
    modle.base_asset = sModle.base_asset;
    modle.recommend = sModle.recommend;
    modle.name = name;
    modle.deal = deal;
    modle.volume = volume;
    modle.high = high;
    modle.open = open;
    modle.last = last;
    modle.low = low;
    modle.tick_size = sModle.tick_size;
    modle.min_quantity = sModle.min_quantity;
    modle.base_asset_precision = sModle.base_asset_precision;
    modle.quote_asset_precision = sModle.quote_asset_precision;
    modle.classes = sModle.classes;
    modle.recommend = sModle.recommend;
    modle.increase = [NSString stringWithFormat:@"%.2f",(last.floatValue - open.floatValue)/open.floatValue];
    modle.IncreaseDegree =  [NSString stringWithFormat:@"%.2f%%",(last.floatValue - open.floatValue)/open.floatValue * 100];
    modle.currency = [EXUnit getBTBPriceWithName:modle.quote_asset Price:modle.last];
   
    [dataArray addObject:modle];
    
    if (modle.recommend.integerValue ==1)
    {
        [recommendArray addObject:modle];
    }
    if ([modle.quote_asset isEqualToString:DICKEY])
    {
        [mutableDic setObject:last forKey:modle.base_asset];
    }
    
    if (dataArray.count ==articlelArray.count)
    {
        
        NSArray *result = [dataArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
            HomeModle * modle1 = obj1;
            HomeModle * modle2 = obj2;
            
            if ([modle1.IncreaseDegree floatValue] < [modle2.IncreaseDegree floatValue])
            {
                return NSOrderedDescending;
            }
            else
            {
                return NSOrderedAscending;
            }
            
        }];
        dataArray = [NSMutableArray arrayWithArray:result];
        [dataArray bg_saveArrayWithName:FMDBName_Symbol]; //数组排序之后添加数据库
        [AppDelegate shareAppdelegate].modle = dataArray[0];
        [AppDelegate shareAppdelegate].dictionary = mutableDic;
        callback(dataArray,recommendArray,mutableDic);
 
   }
}
/*更新交易对并切排序返回新的数组  注意***** 这里面的所有耗时循环一定记得抛出去数据流较大会卡主线程
 @param articlelArray 交易对返回到数据数组
 @param deal
 @param volume
 @param high
 @param open
 @param last
 @param low
 @param name
 @param dataArray 排序返回新的数组
 @param recommendArray 推荐的数组
 @param DICKEY 交易对 （cnt CNY）
 @param isGetnews 判断是否获取咯广告接口
 @param isrecommen 已经计算过headview高不需要在计算
 @param tableviewHeadView tableviewHeadView
 @param buttonIndex 1 涨幅榜 2为跌幅榜
 @param mutableDic 最新交易对的价格
 */
+ (void)getUpdataSymbolWithArticlelArray:(NSMutableArray *)articlelArray
                             ataWithDeal:(NSString *)deal
                                  volume:(NSString *)volume
                                    high:(NSString *)high
                                    open:(NSString *)open
                                    last:(NSString *)last
                                     low:(NSString *)low
                                    name:(NSString *)name
                               dataArray:(NSMutableArray *)dataArray
                          recommendArray:(NSMutableArray *)recommendArray
                                  DICKEY:(NSString *)DICKEY
                               isGetnews:(BOOL )isGetnews
                              isrecommen:(BOOL)isrecommen
                       tableviewHeadView:(TableViewHeadview *)tableviewHeadView
                             buttonIndex:(NSInteger )buttonIndex
                              mutableDic:(NSMutableDictionary *)mutableDic
                                callBack:(void(^)(NSMutableArray * dataArray,NSMutableArray * recommendArray,NSMutableDictionary * mutableDic))callback;
{
    SymbolModle * sModle;
    for (int i =0 ; i<articlelArray.count; i++)
    {
        SymbolModle * Symbomodle = articlelArray[i];
        if ([name isEqualToString:Symbomodle.symbol]) {
            
            sModle = articlelArray[i];
            break;
        }
    }
    
    for (int i=0; i<dataArray.count; i++)
    {
        HomeModle * modle  = dataArray[i];
        
        if ([name isEqualToString:modle.name]) {
            
            modle.deal = deal;
            modle.volume = volume;
            modle.high = high;
            modle.open = open;
            modle.last = last;
            modle.low = low;
            modle.classes = sModle.classes;
            modle.increase = [NSString stringWithFormat:@"%.2f",(last.floatValue - open.floatValue)/open.floatValue];
            modle.IncreaseDegree =  [NSString stringWithFormat:@"%.2f%%",(last.floatValue - open.floatValue)/open.floatValue * 100];
            modle.quote_asset = sModle.quote_asset;
            modle.recommend = sModle.recommend;
            modle.base_asset = sModle.base_asset;
            modle.tick_size = sModle.tick_size;
            modle.min_quantity = sModle.min_quantity;
            modle.base_asset_precision = sModle.base_asset_precision;
            modle.quote_asset_precision = sModle.quote_asset_precision;
            modle.currency = [EXUnit getBTBPriceWithName:modle.quote_asset Price:modle.last];
            // 处理耗时操作的代码块...
            if (isGetnews&& !isrecommen &&recommendArray.count >=3)
            {
                [tableviewHeadView uploadSymbol:modle];
            }
            
            [[NSNotificationCenter defaultCenter] postNotificationName:updateSymbolNotificationse object:modle];
            if ([modle.quote_asset isEqualToString:DICKEY])
            {
                for(NSString * akey in mutableDic.allKeys)
                {
                    if (modle.base_asset == akey)
                    {
                        [mutableDic setObject:last forKey:modle.base_asset];
                        break;
                        
                    }
                }
                
            }
            
            break;
            
        }
        
        
    }
    callback(dataArray,recommendArray,mutableDic);
    
}
/*更新FMDB数据*/
+ (void)UpDataFMDBSymbolWithDeal:(NSString *)deal
                          volume:(NSString *)volume
                            high:(NSString *)high
                            open:(NSString *)open
                            last:(NSString *)last
                             low:(NSString *)low
                            name:(NSString *)name
{
    
   dispatch_async(dispatch_get_global_queue(0, 0), ^{ // 处理耗时操作在此次添加
       
       NSArray * array = [NSArray bg_arrayWithName:FMDBName_Symbol];
       for (int i=0; i<array.count; i++)
       {
           HomeModle * modle  = array[i];
           if ([name isEqualToString:modle.name]) {
               modle.deal = deal;
               modle.volume = volume;
               modle.high = high;
               modle.open = open;
               modle.last = last;
               modle.low = low;
               modle.increase = [NSString stringWithFormat:@"%.2f",(last.floatValue - open.floatValue)/open.floatValue];
               modle.IncreaseDegree =  [NSString stringWithFormat:@"%.2f%%",(last.floatValue - open.floatValue)/open.floatValue * 100];
               dispatch_async(dispatch_get_main_queue(), ^{
                 modle.currency = [EXUnit getBTBPriceWithName:modle.quote_asset Price:modle.last];
               
               });
           
               [NSArray bg_updateObjectWithName:FMDBName_Symbol Object:modle Index:i];
               return ;
               
               
           }
           
       }
   });
   
}
#pragma mark - 交易对详情

/*获取交易详情
 @param dic 传的参数
 @param urr 接口名称
 @return isSuccess 成功 数组
 */
+ (void)getAssetInfoWithDic:(NSDictionary *)dic url:(NSString *)url callBack:(void(^)(BOOL isSuccess,id callBack))callback
{
    [self httpHostWithHost:HOSTGET Dic:dic url:url callBack:^(BOOL isSuccess, id callBack) {
        if (isSuccess) {
            NSDictionary *dic = callBack[@"result"];
            callback(YES,dic);
        }else
        {
            
            callback(NO,callBack[@"message"]);
        }
    }];
}


#pragma mark - 行情
/*获取交易对分类
 @param dic 传的参数
 @param urr 接口名称
 @return isSuccess 成功 数组
 */
+ (void)getSymbolClassWithDic:(NSDictionary *)dic url:(NSString *)url callBack:(void(^)(BOOL isSuccess,id callBack))callback
{
    [self httpHostWithHost:HOSTGET Dic:dic url:url callBack:^(BOOL isSuccess, id callBack) {
        if (isSuccess) {
            NSArray * list = callBack[@"result"];
            callback(YES,[SymbolClass mj_objectArrayWithKeyValuesArray:list]);

        }else
        {
            [EXUnit showMessage:callBack[@"message"]];
            callback(NO,callBack[@"message"]);
        }
    }];
}

#pragma mark - 交易
+ (void)getUserAssetsWithDic:(NSDictionary *)dic url:(NSString *)url homeModle:(HomeModle *)modle isSell:(BOOL)isSell callBack:(void(^)(BOOL isSuccess, NSString * sellAvailable, NSString * purchaseAvailable , NSString * balance))callback
{
    
    [self GETWithHost:@"" path:url param:dic cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if ([responseObject[@"code"] integerValue]==0)//成功
        {
          
            NSDictionary *dataDic  = responseObject[@"result"];
            double totalprofit;
            NSArray * keyArray = dataDic.allKeys;
            NSArray *namearray = [modle.name componentsSeparatedByString:@"_"];
            NSString * sellAvailable = @"";
            NSString * purchaseAvailable = @"";
            NSString * balance = @"";
            for (NSString *str in keyArray) {
                NSDictionary *dic = dataDic[str];
                AssetsModle * modle = [[AssetsModle alloc] init];
                modle.name =str;
                modle.available =dic[@"available"];
                modle.c2c_freeze =dic[@"c2c_freeze"];
                modle.freeze =dic[@"freeze"];
                modle.recharge_status =dic[@"recharge_status"];
                modle.trade_status =dic[@"trade_status"];
                modle.withdraw_fee =dic[@"withdraw_fee"];
                totalprofit = modle.available.floatValue + modle.c2c_freeze.floatValue + modle.freeze.floatValue + modle.withdraw_freeze.floatValue;
                modle.totalprofit = totalprofit;
                if ([modle.name isEqualToString:namearray[0]]) {
                    
                    sellAvailable = [NSString stringWithFormat:@"%@",modle.available];
                    
                }else if ([modle.name isEqualToString:namearray[1]])
                {
                    purchaseAvailable = [NSString stringWithFormat:@"%@",modle.available];
                    
                }
                
            }
            if (isSell)
            {
                balance = [NSString stringWithFormat:@"%@",[EXUnit formatternumber:modle.base_asset_precision.intValue assess:sellAvailable]];
            }else
            {
                balance = [NSString stringWithFormat:@"%@",[EXUnit formatternumber:modle.base_asset_precision.intValue assess:purchaseAvailable]];
            }
            callback(YES,sellAvailable,purchaseAvailable,balance);
            
        }
    } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
+ (void)getCancelOrderWithDic:(NSDictionary *)dic url:(NSString *)url callBack:(void(^)(BOOL isSuccess,id callBack))callback;
{
    [self httpHostWithHost:HOSTPOST Dic:dic url:url callBack:^(BOOL isSuccess, id callBack) {
        if (isSuccess) {
            callback(YES,callBack);
            
        }else
        {
            [EXUnit showMessage:callBack[@"message"]];
        }
    }];
}
/*购买&卖出
 @param dic 传的参数
 @param urr 接口名称
 @return isSuccess 成功 数组
 */
+ (void)getTradeWithDic:(NSDictionary *)dic url:(NSString *)url callBack:(void(^)(BOOL isSuccess,id callBack))callback;
{
    
    
    [self POSTWithHost:@"" path:url param:dic cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if ([responseObject[@"code"] integerValue]==0)
        {
             [EXUnit showMessage:responseObject[@"message"]];
            callback(YES,responseObject);
        }else
        {
            [EXUnit showMessage:responseObject[@"message"]];
            callback(NO,responseObject);
            
            
        }
    } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
       callback(NO,error);
        
    }];
}

#pragma mark - C2C 交易

/*银行卡信息
 @param dic 传的参数
 @param urr 接口名称
 @return isSuccess 成功 数组
 */
+ (void)getUserbankWithDic:(NSDictionary *)dic url:(NSString *)url callBack:(void(^)(BOOL isSuccess,id callBack))callback;
{
    [self httpHostWithHost:HOSTGET Dic:dic url:url callBack:^(BOOL isSuccess, id callBack) {
        
        if (isSuccess) {
            NSArray * list = callBack[@"result"];
            NSMutableArray *dataArray = [NSMutableArray array];
            [dataArray addObjectsFromArray:[BankModle mj_objectArrayWithKeyValuesArray:list]];
            callback(YES,dataArray);
        }else
        {
            if ([callBack isEqualToString:@"error"]) { //未登陆情况下包错
                callback(NO,@"error");
            }else
            {
                [EXUnit showMessage:callBack[@"message"]];
            }
        }
        
    }];
}
/*C2C配置信息
 @param dic 传的参数
 @param urr 接口名称
 @return isSuccess 成功 数组
 */
+ (void)getC2CPriceInfoWithDic:(NSDictionary *)dic url:(NSString *)url callBack:(void(^)(BOOL isSuccess,id callBack))callback;
{
    [self GETWithHost:@"" path:url param:dic cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"code"] integerValue]==0)//成功
        {
            callback(YES,responseObject);
            
        }else
        {
            [EXUnit showMessage:responseObject[@"message"]];
   
        }
    } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [EXUnit showMessage:Localized(@"httpsHost_message")];
    }];
   
}
/*未完成订单list
 @param dic 传的参数
 @param urr 接口名称
 @return isSuccess 成功 数组
 */
+ (void)getTradeListWithDic:(NSDictionary *)dic url:(NSString *)url callBack:(void(^)(BOOL isSuccess,id callBack))callback;
{
    
    [self GETWithHost:@"" path:url param:dic cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
   
        
        if ([responseObject[@"code"] integerValue]==0)//成功
        {
              callback(YES,responseObject);
            
        }else
        {
            [EXUnit showMessage:responseObject[@"message"]];
        }
    } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
       
        callback(NO,error);
    }];
}
/*获取支付方式*/
+ (void)getMobilePayDataListWithDic:(NSDictionary *)dic url:(NSString *)url callBack:(void(^)(BOOL isSuccess,id callBack))callback
{
    [self GETWithHost:@"" path:url param:dic cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"code"] integerValue]==0)//成功
        {
            if ([responseObject[@"code"] integerValue]==0)//成功
            {
                callback(YES,responseObject);
                
            }else
            {
                [EXUnit showMessage:responseObject[@"message"]];
                
            }
        }else
        {
            [EXUnit showMessage:responseObject[@"message"]];
        }
    } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
    }];
}
@end
